package com.java110.acct.payment.adapt.pxlc;

import com.alibaba.fastjson.JSONObject;
import com.java110.acct.payment.adapt.pxlc.utils.HttpConnectUtils;
import com.java110.acct.smo.IQrCodePaymentSMO;
import com.java110.core.client.RestTemplate;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.core.factory.WechatFactory;
import com.java110.core.log.LoggerFactory;
import com.java110.dto.payment.PaymentPoolValueDto;
import com.java110.dto.wechat.OnlinePayDto;
import com.java110.dto.wechat.SmallWeChatDto;
import com.java110.intf.acct.IOnlinePayV1InnerServiceSMO;
import com.java110.intf.acct.IPaymentPoolValueV1InnerServiceSMO;
import com.java110.intf.store.ISmallWeChatInnerServiceSMO;
import com.java110.po.wechat.OnlinePayPo;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.constant.WechatConstant;
import com.java110.utils.util.PayUtil;
import com.java110.vo.ResultVo;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 微信支付
 */
@Service
public class QrCodePxlcPaymentAdapt implements IQrCodePaymentSMO {
    private static Logger logger = LoggerFactory.getLogger(QrCodePxlcPaymentAdapt.class);

    //微信支付
    public static final String DOMAIN_WECHAT_PAY = "WECHAT_PAY";
    // 微信服务商支付开关
    public static final String WECHAT_SERVICE_PAY_SWITCH = "WECHAT_SERVICE_PAY_SWITCH";

    //开关ON打开
    public static final String WECHAT_SERVICE_PAY_SWITCH_ON = "ON";


    private static final String WECHAT_SERVICE_APP_ID = "SERVICE_APP_ID";

    private static final String WECHAT_SERVICE_MCH_ID = "SERVICE_MCH_ID";

    private static final SimpleDateFormat timeforamt=new SimpleDateFormat("yyyyMMddHHmmss");


    @Autowired
    private ISmallWeChatInnerServiceSMO smallWeChatInnerServiceSMOImpl;

    @Autowired
    private RestTemplate outRestTemplate;

    @Autowired
    private IPaymentPoolValueV1InnerServiceSMO paymentPoolValueV1InnerServiceSMOImpl;

    @Autowired
    private IOnlinePayV1InnerServiceSMO onlinePayV1InnerServiceSMOImpl;

    @Override
    public ResultVo pay(String communityId, String orderNum, double money, String authCode, String feeName, String paymentPoolId) throws Exception {
        logger.info("【小程序支付】 统一下单开始, 订单编号=" + orderNum);
        SortedMap<String, String> resultMap = new TreeMap<String, String>();
        //生成支付金额，开发环境处理支付金额数到0.01、0.02、0.03元
        double payAmount = PayUtil.getPayAmountByEnv(MappingCache.getValue(MappingConstant.ENV_DOMAIN, "HC_ENV"), money);
        //添加或更新支付记录(参数跟进自己业务需求添加)

        Map<String, String> resMap = null;
        logger.debug("resMap=" + resMap);
        String systemName = MappingCache.getValue(WechatConstant.WECHAT_DOMAIN, WechatConstant.PAY_GOOD_NAME);
        SmallWeChatDto shopSmallWeChatDto = null;
        SmallWeChatDto smallWeChatDto = new SmallWeChatDto();
        smallWeChatDto.setObjId(communityId);
        List<SmallWeChatDto> smallWeChatDtos = smallWeChatInnerServiceSMOImpl.querySmallWeChats(smallWeChatDto);
        if (smallWeChatDtos == null && smallWeChatDtos.size() < 1) {
            shopSmallWeChatDto = new SmallWeChatDto();
            shopSmallWeChatDto.setObjId(communityId);
            shopSmallWeChatDto.setAppId(MappingCache.getValue(WechatConstant.WECHAT_DOMAIN, "appId"));
            shopSmallWeChatDto.setAppSecret(MappingCache.getValue(WechatConstant.WECHAT_DOMAIN, "appSecret"));
        } else {
            shopSmallWeChatDto = smallWeChatDtos.get(0);
        }

        PaymentPoolValueDto paymentPoolValueDto = new PaymentPoolValueDto();
        paymentPoolValueDto.setPpId(paymentPoolId);
        List<PaymentPoolValueDto> paymentPoolValueDtos = paymentPoolValueV1InnerServiceSMOImpl.queryPaymentPoolValues(paymentPoolValueDto);

        if (paymentPoolValueDtos == null || paymentPoolValueDtos.isEmpty()) {
            throw new IllegalArgumentException("配置错误,未配置参数");
        }

        String ORGID = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "ORGID"); // 客户编号
        String ORGMERCODE = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "ORGMERCODE"); // 设备号
        String ORGTERMNO = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "ORGTERMNO"); // 终端号
        String EASYPAY_PUBLIC_KEY = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "EASYPAY_PUBLIC_KEY");
        String MD5_SING_KEY = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "MER_RSA_PRIVATE_KEY"); // MD5 加密参数


        if (feeName.length() > 127) {
            feeName = feeName.substring(0, 126);
        }

        String totalFee = String.valueOf(new BigDecimal(payAmount)
                .multiply(new BigDecimal("100"))
                .intValue()); // 直接截断小数部分



        JsApi request = new JsApi();
        request.setTxn_num("unified_micro_pay"); // 刷卡支付
        request.setVersion("3.0");
        request.setMch_create_ip("117.158.14.7"); // ip
        request.setSub_appid(smallWeChatDto.getAppId());
        request.setDate_time(timeforamt.format(new Date()));
        request.setMcht_id(ORGID); // 商户号
        request.setDev_id(ORGTERMNO); // 终端号
        request.setOut_order_no(orderNum); // 订单号
        request.setNonce_str(RandomStringUtils.randomAlphabetic(12)); // 随机串
        request.setTotal_fee(totalFee);
        request.setFee_type("CNY");
        request.setBody(feeName);
        request.setAuthCode(authCode);



        // 附加数据
        JsApi.HeadAttach head_attach = new JsApi.HeadAttach();
        head_attach.setDev_sp("landi");
        head_attach.setDev_model("E350G");
        head_attach.setLat("121.483527");
        head_attach.setLng("31.22134");
        head_attach.setDev_sn(ORGMERCODE);
        head_attach.setDev_version("liandiv3.2");
        head_attach.setStation("460|00|14382|44724|24|");
        request.setHead_attach(head_attach);

        request.setSign(BasePay.calMD5(JSONObject.toJSONString(request), MD5_SING_KEY));

        System.out.println("\n请求报文：" + JSONObject.toJSONString(request));
        String response = HttpConnectUtils.sendHttpSRequest(BasePay.BASE_URL, JSONObject.toJSONString(request), "JSON", null);
        System.out.println("\n响应报文：" + response);

        doSaveOnlinePay(shopSmallWeChatDto, "-1", orderNum, feeName, payAmount,
                OnlinePayDto.STATE_WAIT, "待支付",paymentPoolValueDtos.get(0).getPpId());

        JSONObject paramOut = JSONObject.parseObject(response);
        if (!"000000".equals(paramOut.getString("return_code"))) {
            throw new IllegalArgumentException("支付失败" + paramOut.getString("return_msg"));
        }

        if ("000000".equals(paramOut.getString("return_code"))) {
            doUpdateOnlinePay(orderNum, OnlinePayDto.STATE_COMPILE, "支付成功");
            return new ResultVo(ResultVo.CODE_OK, "成功");
        } else {
            return new ResultVo(ResultVo.CODE_WAIT_PAY, "等待用户支付中");
        }
    }

    public ResultVo checkPayFinish(String communityId, String orderNum, String paymentPoolId) {
        Map<String, String> result = null;
        PaymentPoolValueDto paymentPoolValueDto = new PaymentPoolValueDto();
        paymentPoolValueDto.setPpId(paymentPoolId);
        paymentPoolValueDto.setCommunityId(communityId);
        List<PaymentPoolValueDto> paymentPoolValueDtos = paymentPoolValueV1InnerServiceSMOImpl.queryPaymentPoolValues(paymentPoolValueDto);


        if (paymentPoolValueDtos == null || paymentPoolValueDtos.isEmpty()) {
            throw new IllegalArgumentException("配置错误,未配置参数");
        }
        String ORGID = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "ORGID"); // 客户编号
        String ORGMERCODE = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "ORGMERCODE");
        String ORGTERMNO = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "ORGTERMNO");
        String EASYPAY_PUBLIC_KEY = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "EASYPAY_PUBLIC_KEY");
        String MD5_SING_KEY = PaymentPoolValueDto.getValue(paymentPoolValueDtos, "MER_RSA_PRIVATE_KEY");

        JsApi request = new JsApi();
        request.setTxn_num("unified_js_pay"); // 小程序支付
        request.setVersion("3.0");
        request.setMch_create_ip("117.158.14.7"); // ip
        request.setDate_time(timeforamt.format(new Date()));
        request.setMcht_id(ORGID); // 商户号
        request.setDev_id(ORGTERMNO); // 终端号
        request.setOut_order_no(orderNum); // 订单号

        request.setNonce_str(RandomStringUtils.randomAlphabetic(12)); // 随机串

        // 附加数据
        JsApi.HeadAttach head_attach = new JsApi.HeadAttach();
        head_attach.setDev_sp("landi");
        head_attach.setDev_model("E350G");
        head_attach.setLat("121.483527");
        head_attach.setLng("31.22134");
        head_attach.setDev_sn(ORGMERCODE);
        head_attach.setDev_version("liandiv3.2");
        head_attach.setStation("460|00|14382|44724|24|");
        request.setHead_attach(head_attach);

        request.setSign(BasePay.calMD5(JSONObject.toJSONString(request), MD5_SING_KEY));

        String response = null;
        try {
            response = HttpConnectUtils.sendHttpSRequest(BasePay.BASE_URL, JSONObject.toJSONString(request), "JSON", null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("\n响应报文：" + response);

        JSONObject paramOut = JSONObject.parseObject(response);
        if (!"000000".equals(paramOut.getString("return_code"))) {
            throw new IllegalArgumentException("支付失败" + paramOut.getString("return_msg"));
        }

        if ("1".equals(paramOut.getString("org_txn_state"))) {
            doUpdateOnlinePay(orderNum, OnlinePayDto.STATE_COMPILE, "支付成功");

            return new ResultVo(ResultVo.CODE_OK, "成功");
        } else {
            return new ResultVo(ResultVo.CODE_ERROR, "等待用户支付中");
        }

    }

    private void doSaveOnlinePay(SmallWeChatDto smallWeChatDto, String openId, String orderId, String feeName,
                                 double money, String state, String message,String ppId) {
        OnlinePayPo onlinePayPo = new OnlinePayPo();
        onlinePayPo.setAppId(smallWeChatDto.getAppId());
        onlinePayPo.setMchId(smallWeChatDto.getMchId());
        onlinePayPo.setMessage(message.length() > 1000 ? message.substring(0, 1000) : message);
        onlinePayPo.setOpenId(openId);
        onlinePayPo.setOrderId(orderId);
        onlinePayPo.setPayId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_orderId));
        onlinePayPo.setPayName(feeName);
        onlinePayPo.setRefundFee("0");
        onlinePayPo.setState(state);
        onlinePayPo.setTotalFee(money + "");
        onlinePayPo.setTransactionId(orderId);
        onlinePayPo.setPaymentPoolId(ppId);
        onlinePayV1InnerServiceSMOImpl.saveOnlinePay(onlinePayPo);
    }

    private void doUpdateOnlinePay(String orderId, String state, String message) {
        OnlinePayPo onlinePayPo = new OnlinePayPo();
        onlinePayPo.setMessage(message.length() > 1000 ? message.substring(0, 1000) : message);
        onlinePayPo.setOrderId(orderId);
        onlinePayPo.setState(state);
        onlinePayV1InnerServiceSMOImpl.updateOnlinePay(onlinePayPo);
    }
}
